<template>
  <div class="container-login" v-if="!formView.loginState">
    <div class="un-login" v-if="!formView.registerState">
      <div class="user-info">
        <div class="section-title">登录</div>

        <el-input class="username" v-model="formLogin.username" placeholder="用户名" type="text" style="width: 200px"/>
        <el-input class="password" v-model="formLogin.password" placeholder="密码" type="password"
                  style="width: 200px"/>
        <div class="buttons">
          <button @click="login">登录</button>
          <button @click="formView.registerState=true">去注册</button>
        </div>
      </div>
    </div>
    <div class="un-register" v-else>
      <div class="user-info">
        <div class="section-title">注册</div>
        <div>
          <el-upload
              ref="upload"
              :action="baseURL+'/file/upload'"
              list-type="picture-card"
              :auto-upload="true"
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="handleChange"
              v-model:file-list="fileList"
          >
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>
        </div>
        <el-input class="username" v-model="formLogin.nickname" placeholder="昵称" type="text" style="width: 200px"/>
        <el-input class="username" v-model="formLogin.username" placeholder="用户名" type="text" style="width: 200px"/>
        <el-input class="password" v-model="formLogin.password" placeholder="密码" type="password"
                  style="width: 200px"/>
        <div class="buttons">
          <button @click="register()">注册</button>
          <button @click="formView.registerState=false">去登录</button>
        </div>
      </div>
    </div>
  </div>

  <div class="container2" v-if="formView.loginState">
    <div class="user-info">

      <div v-show="editState">
        <el-upload
            ref="upload"
            :action="baseURL+'/file/upload'"
            list-type="picture-card"
            :auto-upload="true"
            :limit="1"
            :on-exceed="handleExceed"
            :on-change="handleChange"
            v-model:file-list="fileList"
        >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
      </div>

      <img :src="baseURL+'/file/download?filename=' + formInfo.img" v-show="!editState"
           alt="User Avatar" width="100" height="100">
      <div class="username">{{ formInfo.username }}</div>

      <el-input class="account" style="width: 100px" v-model="formInfo.nickname" v-show="editState"></el-input>
      <div class="account" v-show="!editState">{{ formInfo.nickname }}</div>

      <div class="buttons">
        <button @click="save" v-show="editState">保存</button>
        <button @click="openEditModal" v-show="!editState">修改信息</button>
        <button @click="logout">退出登录</button>
      </div>
    </div>
    <div class="favorites">
      <div class="section-title">收藏记录</div>
      <div class="section-links">
        <a href="#" @click.prevent="updatePosts('myCollection')">我的收藏</a>
        <a href="#" @click.prevent="updatePosts('myPosts')">我的发帖</a>
      </div>
      <div class="section-title">{{ postType }}</div>
      <div class="posts" id="postContainer">
        <div v-for="(post, index) in paginatedPosts" :key="index" class="post">
          <img :src="baseURL+'/file/download?filename=' + post.user_img" v-show="!editState"
               alt="User Avatar" width="100" height="100">
          <h3 class="post-title">{{ post.title }}</h3>
          <img v-if="post.image" :src="post.image" alt="Post Image">
          <p class="post-content">{{ post.content }}</p>
        </div>
      </div>
      <div class="control_button">
        <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
        <div>
          第 {{ currentPage }} 页，共 {{ totalPages }} 页
        </div>
        <button @click="nextPage" :disabled="!hasNextPage">下一页</button>
      </div>

    </div>
  </div>
</template>


<script lang="ts" setup>
import {onMounted, reactive, ref, computed} from 'vue';
import {useRouter} from "vue-router";
import {ElMessage, genFileId, UploadFile, UploadInstance, UploadRawFile, UploadUserFile} from "element-plus";
import {getInfoApi, loginApi, registerApi, saveApi} from "@/api/login";
import {getToken, logoutTool, setToken} from "@/utils/auth";
import {getMyFavoritesApi, getMyPostsApi} from "@/api/post";
import type {UploadProps} from 'element-plus'
import {Delete, Plus, ZoomIn} from "@element-plus/icons-vue";
import {baseURL} from "@/api/request";

const formView = reactive({
  loginState: false,
  registerState: false
});
const username = ref('用户名');
const account = ref('用户账号');
const posts = ref<any[]>([]);
const postType = ref("我的帖子");
const currentPage = ref(1);
const postsPerPage = 3;

const totalPages = computed(() => {
  return Math.ceil(posts.value.length / postsPerPage);
});

const paginatedPosts = computed(() => {
  const start = (currentPage.value - 1) * postsPerPage;
  const end = start + postsPerPage;
  return posts.value.slice(start, end);
});

const hasNextPage = computed(() => {
  return currentPage.value * postsPerPage < posts.value.length;
});

const formLogin = reactive({
  username: "",
  nickname: "",
  password: "",
  img: "",
});

const router = useRouter();
const loading = ref(false);

onMounted(() => {
  getView();
  getData();

});
const formInfo = reactive({
  username: "",
  nickname: "",
  img: "",
  id: ""
});

function getInfo() {
  getInfoApi().then((res: any) => {
    Object.assign(formInfo, res.data)
  })
}

function getData() {
  if (formView.loginState) {
    getMyPosts();
    getInfo()
  }

}

function updatePosts(section: string) {
  currentPage.value = 1;
  switch (section) {
    case 'myCollection':
      getMyFavorites();
      break;
    case 'myPosts':
      getMyPosts();
      break;
    default:
      posts.value = [];
      break;
  }
}

function getMyPosts() {
  getMyPostsApi().then((res: any) => {
    posts.value = res.data;
    postType.value = "我的帖子";
  });
}

function getMyFavorites() {
  getMyFavoritesApi().then((res: any) => {
    posts.value = res.data;
    postType.value = "我的收藏";
  });
}

function getView() {
  const token = getToken();
  formView.loginState = !!token;
}

function login() {
  if (!formLogin.username) {
    ElMessage.warning("请输入账号！");
    return false;
  } else if (!formLogin.password) {
    ElMessage.warning("请输入密码！");
    return false;
  } else {
    ElMessage.closeAll();
    loginApi(formLogin).then((response: any) => {
      setToken(response.data.token);
      formView.loginState = true
      getData()
      ElMessage.success(response.detail);
      formView.loginState = true;
    });
  }
}

function register() {
  if (!formLogin.username) {
    ElMessage.warning("请输入账号！");
    return false;
  } else if (!formLogin.password) {
    ElMessage.warning("请输入密码！");
    return false;
  } else if (!formLogin.nickname) {
    ElMessage.warning("请输入昵称！");
    return false;
  } else {
    ElMessage.closeAll();
    registerApi(formLogin).then((response: any) => {
      setToken(response.data.token);
      formView.loginState = true
      getData()
      ElMessage.success(response.detail);
      formView.loginState = true;
    });
  }
}

function logout() {
  logoutTool();
  getView();
}

function prevPage() {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
}

function nextPage() {
  if (hasNextPage.value) {
    currentPage.value++;
  }
}

const editState = ref(false)

function openEditModal() {
  // 实现打开模态框的逻辑
  editState.value = true
}


const disabled = ref(false)


const upload = ref<UploadInstance>()

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

const fileList = ref<UploadUserFile[]>([])
const handleChange: UploadProps['onExceed'] = (files) => {
  // 打印所有文件的名字
  fileList.value.forEach(file => {
    formInfo.img = file.name
    formLogin.img = file.name
  });

}

const submitUpload = () => {
  upload.value!.submit()
}

function save() {
  // 实现打开模态框的逻辑
  saveApi(formInfo).then((res) => {
    editState.value = false
  })
}
</script>

<style>
.post-title{
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;/*显示几行*/
  overflow: hidden;
}
.post-content{
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 8;/*显示几行*/
  overflow: hidden;
}
.el-upload-list--picture-card {
  display: inline-flex;
  flex-wrap: wrap;
  flex-direction: column !important;
}
</style>
<style scoped>
.post-title{
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;/*显示几行*/
  overflow: hidden;
}
.post-content{
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 8;/*显示几行*/
  overflow: hidden;
}
.el-upload-list--picture-card {
  display: inline-flex;
  flex-wrap: wrap;
  flex-direction: column !important;
}




.avatar-uploader .avatar {
  display: block;
  border-radius: 50%;
}

.avatar-uploader .el-upload {

  border: 1px dashed var(--el-border-color);
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}


/*左右分区显示格式——出现在个人主页中*/
.container2 {
  display: flex;
  max-width: 1100px;
  height: 600px;
  margin: 20px auto;
  background-color: transparent;
  padding: 20px;
}

.user-info {
  flex: 1; /* 左边部分占四分之一 */
  padding: 20px;
  background-color: #f0f0f0;
  border-right: 1px solid #ccc;
  display: flex;
  height: 600px;
  flex-direction: column;
  align-items: center; /* 左侧内容垂直居中显示 */
  justify-content: center; /* 左侧内容水平居中显示 */
}

.user-info img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin-bottom: 10px;
}

.user-info .username,
.user-info .account {
  margin-bottom: 10px;
  text-align: center;
}

.user-info .buttons {
  margin-top: auto; /* 将按钮置于左侧部分底部 */
  display: flex;
  flex-direction: column;
  align-items: center; /* 让按钮水平居中显示 */
  justify-content: center; /* 让按钮垂直居中显示 */
}

.user-info .buttons button {
  margin-bottom: 10px; /* 按钮之间添加一些间距 */
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
}

.favorites {
  flex: 3;
  display: flex;
  width: 300px;
  height: 600px;
  background-color: #fff;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  flex-direction: column;
  justify-content: space-between;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.section-links {
  margin-bottom: 20px;
  display: flex;
}

.section-links a {
  display: block;
  padding: 10px 20px; /* 保持链接的内边距 */
  text-decoration: none;
  color: #333;
  font-size: 16px;
}

.control_button {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 0 60px 0 60px;

}

.control_button button {
  padding: 3px 15px 3px 15px;
  background-color: #808080;
  font-family: '华文楷体', Arial, Helvetica, sans-serif;
  color: white;
  border-radius: 5px;
  border: 0;
}


.posts {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  height: 600px;
}

.post {
  flex: 1 0 auto;
  width: calc(33.33% - 50px); /* 计算每个帖子的宽度，考虑到间距 */
  max-width: 211.6px;
  height: 360px !important;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  margin-right: 20px; /* 右侧间距 */
  float: left; /* 左浮动使其横向排列 */
  box-sizing: border-box; /* 包含边框在内的盒子模型 */
}

.post img {
  max-width: 100%;
  height: auto;
  border-radius: 5px;
}


.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.user-info img {
  border-radius: 50%;
}

.username, .account {
  margin: 10px 0;
}

.buttons {
  margin: 20px 0;
}

.favorites .section-title {
  font-weight: bold;
  /*margin-top: 20px;*/
}

.section-links a {
  margin-right: 15px;
}

.posts .post {
  margin-top: 20px;
}
</style>
